package org.ax.controller;

import org.ax.data.Result;
import org.ax.pojo.sys.User;
import org.ax.service.sys.UserService;
import org.ax.util.RedisUtil;
import org.ax.websocket.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 编程人:赵浩鑫
 * 时间:2021-01-29-11:01
 */
@Controller
public class WeIComeController {
    @RequestMapping("/")
    public String login(Map<String,Object> map){
        map.put("name", "Welcome to use thymeleaf");
        return "login";
    }

    public String messageTemplate(Message message,String userId){
        String messageStr="";
        if(message.getType().equals("sys")){
            messageStr="<div class=\"system\">\n" +
                    "              <p class=\"message_system\">\n" +
                    "                <span class=\"content\">"+message.getFromName()+" 加入群聊</span>\n" +
                    "              </p>\n" +
                    "            </div><br>";
        }else{
            if(message.getFromId().equals(userId)){
                messageStr+=" <div class=\"message-box\">\n" +
                        "              <div class=\"my message\">\n" +
                        "                <img src=\""+message.getFromImg()+"\" alt=\"\" class=\"avatar\">\n" +
                        "                <div class=\"content\">\n" +
                        "                  <div class=\"bubble\">\n" +
                        "                    <div class=\"bubble_cont\">"+message.getMessageText()+"</div>\n" +
                        "                  </div>\n" +
                        "                </div>\n" +
                        "              </div>\n" +
                        "            </div>";
            }else{
                messageStr+="<div class=\"message-box\">\n" +
                        "              <div class=\"other message\">\n" +
                        "                <img src=\""+message.getFromImg()+"\" alt=\"\" class=\"avatar\">\n" +
                        "                <div class=\"nickname\">"+message.getFromName()+"</div>\n" +
                        "                <div class=\"content\">\n" +
                        "                  <div class=\"bubble\">\n" +
                        "                    <div class=\"bubble_cont\">"+message.getMessageText()+"</div>\n" +
                        "                  </div>\n" +
                        "                </div>\n" +
                        "              </div>\n" +
                        "            </div> ";
            }
        }
        return messageStr;
    }

    @Autowired
    HttpSession httpSession;
    @Autowired
    UserService userService;
    @Autowired
    RedisUtil redisUtil;
    @GetMapping("/home/console.html")
    public String console(Map map){
        User user=(User)httpSession.getAttribute("user");
//        redisUtil.set("hypertext",redisUtil.get("hypertext")==null?
//                "<div class=\"box-bd\" data=\"*\"></div>":redisUtil.get("hypertext"));
//        System.err.println("消息"+redisUtil.get("hypertext"));
        String messageInfo="";

        List<Message> messageList=(List<Message>)redisUtil.get("messageList");
        if (messageList!=null){
            for (Message message : messageList) {
                messageInfo+=messageTemplate(message, user.getId());
            }
        }

        map.put("hypertext",messageInfo);
        map.put("userList", userService.friendlyUser(user.getId()));
        return "console";
    }
    @RequestMapping("/upload")
    public String upload(){
        return "upload2";
    }
    @ResponseBody
    @RequestMapping(value = "/unthor",produces = "text/html;charset=utf-8")
    public String unthor(){
        return "<h1 style='color:red'>抱歉没有访问权限</h1>";
    }

//    上传
    @RequestMapping(value = "/uploadHead.do", method = RequestMethod.POST)
    @ResponseBody
    public int uploadHead(@RequestParam("file") MultipartFile file, HttpSession session) {
        try {
            if (file != null) {
                //获取文件名
                String fileName = file.getOriginalFilename();
                //截取扩展名
                String extName = fileName.substring(fileName.lastIndexOf("."));
                List list = new ArrayList();
                list.add(".jpg");
                list.add(".png");
                list.add(".jpeg");
                list.add(".gif");
                if(list.contains(extName.toLowerCase())){

                    //01获取服务器项目部署的路径，并在根目录下创建 myphoto 目录
                    //String realPath = session.getServletContext().getRealPath("myphoto");
                    //02也可以直接定义文件路径
                    String realPath = "G:\\img";

                    String photoFileName = new Date().getTime()+extName;
                    String descPath = realPath + "\\" + photoFileName;
                    System.out.println(descPath);
                    file.transferTo(new File(realPath,photoFileName));
                    return 1;//成功
                }else {
                    return -1;//文件类型不正确
                }
            }else {
                return 0;//上传文件为空
            }
        } catch (Exception e) {
            e.printStackTrace();
            return -1;//上传异常
        }
    }

    //上传文件
    @ResponseBody
    @RequestMapping(value = "/uploadFile")
    public Object uploadFile(HttpServletRequest request, @RequestPart("file") MultipartFile file) throws IOException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSS");
        String res = sdf.format(new Date());
        //服务器上使用
        // String rootPath =request.getServletContext().getRealPath("/resource/uploads/");//target的目录
        //本地使用
        String rootPath ="G:/images";
        //原始名称
        String originalFilename = file.getOriginalFilename();
        //新的文件名称
        String newFileName = res+originalFilename.substring(originalFilename.lastIndexOf("."));
        //创建年月文件夹
        Calendar date = Calendar.getInstance();
        File dateDirs = new File(date.get(Calendar.YEAR)
                + File.separator + (date.get(Calendar.MONTH)+1));
        //新文件
        File newFile = new File(rootPath+File.separator+dateDirs+File.separator+newFileName);
        //判断目标文件所在的目录是否存在
        if(!newFile.getParentFile().exists()) {
            //如果目标文件所在的目录不存在，则创建父目录
            newFile.getParentFile().mkdirs();
        }
        System.out.println(newFile);
        //将内存中的数据写入磁盘
        file.transferTo(newFile);
        //完整的url
        String fileUrl =  "/uploads/"+date.get(Calendar.YEAR)+ "/"+(date.get(Calendar.MONTH)+1)+ "/"+ newFileName;
        Map<String,Object> map = new HashMap<String,Object>();
        Map<String,Object> map2 = new HashMap<String,Object>();
        map.put("code",0);//0表示成功，1失败
        map.put("msg","上传成功");//提示消息
        map.put("data",map2);
        map2.put("src",fileUrl);//图片url
        map2.put("title",newFileName);//图片名称，这个会显示在输入框里
//        String result = new JSONObject(map).toString();
        return map;
    }

    @ResponseBody
    @PostMapping("/myUpload")
    public String myUpload(@RequestPart("file") MultipartFile file){
        if(!file.isEmpty()){
            try {
                file.transferTo(new File("G:/images/",file.getOriginalFilename()));
                return "上传成功";
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return "上传失败";
    }

    @Autowired
    Result result;
    @ResponseBody
    @PostMapping("/weCantUpload")
    public Result weCantUpload(@RequestPart("file") MultipartFile[] file) throws IOException {
        String fileName="";
        String resultName="";
        if(file.length>0){
            for (MultipartFile multipartFile : file) {
                String prefix=String.valueOf(System.currentTimeMillis());
                String suffix=multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().indexOf('.'));
                fileName=prefix+suffix;
                multipartFile.transferTo(new File("F:\\Y2data\\SSM\\SSM-production\\src\\main\\resources\\img\\message\\"+fileName));
                resultName+=fileName+",";
            }
        }
        resultName=resultName.substring(0, resultName.length()-1);
        result.setMsg(resultName);
        return result;
    }
}
